<template>
  <el-dialog :visible="visible" width="40%" @close="handleClose">
    <el-radio-group slot="title" v-model="payWay" @change="handleChangePayWay">
      <el-radio-button label="BALANCE">余额支付</el-radio-button>
      <!-- <el-radio-button label="ALIPAY">支付宝</el-radio-button>-->
      <el-radio-button label="WECHAT">微信</el-radio-button>
    </el-radio-group>
    <p class="tip" style="text-align: center">
      请在下单30分钟内完成支付,剩余时间：
      <el-statistic
        style="fonst-size: 12px"
        ref="statistic"
        format="HH:mm:ss"
        :value="deadline"
        time-indices
      ></el-statistic>
    </p>
    <div class="payContent" v-if="payWay == 'BALANCE'" v-loading="loading">
      <strong>
        我的余额：{{
        balanceInfo && balanceInfo.memberBalanceAmount | filterPriceFormat
        }}
      </strong>
      <br />
      <br />
      <strong>本次需要：{{ payAmount | filterPriceFormat }}</strong>
    </div>
    <div class="payContent" v-else>
      <strong>待支付金额：{{ payAmount | filterPriceFormat }}</strong>

      <div style="height:200px;width：200px" v-loading="loading">
        <TheQrCode class="qrCode" :width="200" :height="200" :value="codeUrl" v-if="codeUrl" />
      </div>
    </div>
    <span slot="footer" v-if="payWay == 'BALANCE'" class="dialog-footer">
      <el-button type="primary" @click="submit">确 定 支 付</el-button>
    </span>
    <span slot="footer" v-else class="dialog-footer">
      <el-button type="primary" @click="getPayStatus">支 付 完 成</el-button>
    </span>
  </el-dialog>
</template>
<script>
import {
  apiOrderBGetPay,
  apiExtraServiceOrderGetPay,
  apiGetPaymentStatusByOrderCode
} from "@/api/order.js";
import TheQrCode from "@/components/TheQrCode/index.vue";
import { apiMemberBalanceGetMemberBalance } from "@/api/statements.js";

export default {
  components: { TheQrCode },
  props: {
    dataId: {
      type: String,
      default: ""
    },
    dataType: {
      type: String,
      default: "MERCHANT"
    }
  },
  data() {
    return {
      visible: false,
      payWay: "BALANCE",
      params: {},
      codeUrl: "",
      loading: false,
      payAmount: 0,
      mode: "order", //order 常规订单 extraOrder 加价订单
      balanceInfo: { memberBalanceAmount: 0 },
      hilarityTime: null,
      timer: null
    };
  },
  computed: {
    deadline() {
      if (this.hilarityTime) {
        const downTime =
          new Date(this.hilarityTime).getTime() + 30 * 60 * 1000 - Date.now();
        console.log(downTime, "downTime");
        return Date.now() + (downTime > 0 ? downTime : 0);
      } else {
        return 0;
      }
    }
  },
  mounted() {},

  methods: {
    /**
     * @param {string} payWay 默认的方式
     * @param {object} ext 附加参数 eg:订单id
     * @param {string} payAmount 订单金额:
     *
     */
    onShow({ payWay, mode, payAmount, ext, hilarityTime } = {}) {
      this.visible = true;
      this.payWay = payWay;
      this.params = ext;
      this.payAmount = payAmount;
      this.mode = mode;
      this.hilarityTime = hilarityTime;
      this.$nextTick(() => {
        this.handleChangePayWay();
      });
    },
    submit() {
      if (["ALIPAY", "WECHAT"].includes(this.payWay)) {
        this.visible = false;
      } else {
        this.$confirm("是否确认余额支付?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            if (this.mode == "extraOrder") {
              apiExtraServiceOrderGetPay({
                ...this.params,
                payMethod: this.payWay
              }).then(res => {
                this.visible = false;
                this.$emit("paySuccess");
              });
            } else {
              apiOrderBGetPay({
                ...this.params,
                payMethod: this.payWay,
                tradeType: this.payWay == "BALANCE" ? "" : this.params.tradeType
              }).then(res => {
                this.visible = false;
                this.$emit("paySuccess");
              });
            }
          })
          .catch(() => {});
      }
    },
    async handleChangePayWay(e) {
      this.loading = true;
      const { mode } = this;
      let res = null;
      if (["ALIPAY", "WECHAT"].includes(this.payWay)) {
        if (mode == "order") {
          res = await apiOrderBGetPay({
            ...this.params,
            payMethod: this.payWay,
            tradeType: this.payWay == "BALANCE" ? "" : this.params.tradeType
          });
        } else if (mode == "extraOrder") {
          res = await apiExtraServiceOrderGetPay({
            ...this.params,
            payMethod: this.payWay
          });
        }
        if (res.code == "SUCCESS") {
          try {
            const { code, msg, data } = res.data.payResult;
            if (code == "SUCCESS") {
              if (this.payWay == "WECHAT") {
                const { code_url, codeUrl } = data;
                this.codeUrl = codeUrl || code_url;
                setTimeout(() => {
                  this.getPayStatus();
                }, 3000);
              } else if (this.payWay == "ALIPAY") {
              }
            } else {
              this.$message({
                type: "warning",
                message: msg
              });
            }
          } catch (error) {
            this.$message({
              type: "warning",
              message: "支付唤起异常，联系管理员"
            });
          }
          this.loading = false;
        } else {
          this.loading = false;
        }
      } else if (["BALANCE"].includes(this.payWay)) {
        // 获取余额
        apiMemberBalanceGetMemberBalance({
          dataId: this.dataId,
          dataType: this.dataType
        })
          .then(res => {
            this.balanceInfo = res.data;
            this.loading = false;
          })
          .catch(() => {
            this.loading = false;
          });
      }
    },
    handleClose() {
      this.visible = false;
      clearTimeout(this.timer);
      this.timer = null;
      this.$emit("payCancel");
    },
    /*
     * NOT_PAY 未支付
     * PAY_COMPLETE 支付完成
     * PAY_FAILURE支付失败
     * PAY_TIMEOUT 支付失败
     */
    getPayStatus() {
      clearTimeout(this.timer);
      this.timer = null;
      const params = {
        orderCode: this.params.serviceOrderId || this.params.extraServiceOrderId
      };
      const res = null;
      apiGetPaymentStatusByOrderCode(params).then(res => {
        if (res.code == "SUCCESS") {
          if (!res.data) {
            this.$message({
              message: "未查询到订单信息",
              type: "warning"
            });
            return;
          }
          if (res.data.tradeState == "PAY_COMPLETE") {
            clearTimeout(this.timer);
            this.timer = null;
            this.visible = false;
            this.$emit("paySuccess");
          } else {
            this.timer = setTimeout(() => {
              this.getPayStatus();
            }, 2000);
          }
        } else {
          this.timer = setTimeout(() => {
            this.getPayStatus();
          }, 2000);
        }
      });
    }
  }
};
</script>
<style scoped lang="scss">
.tip {
  font-size: 12px;
  color: #999;
}
.payContent {
  text-align: center;
  img {
    width: 200px;
    height: 200px;
    background-color: #ddd;
  }
}
::v-deep .el-dialog__footer,
::v-deep .el-dialog__header {
  text-align: center;
}
::v-deep .el-statistic {
  width: auto;
  display: inline-block;
  .con {
    color: red !important;
    .number {
      font-size: 16px !important;
      line-height: auto;
    }
  }
}
</style>
